package org.bbsoft.catchme.model;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ApplicationScoped
public class EntityManagerServiceProducer {

	private static final Logger logger = LoggerFactory
			.getLogger(EntityManagerServiceProducer.class);

	private EntityManagerFactory entityManagerFactory;

	public EntityManagerServiceProducer() {
		/* Does nothing */
	}

	@PostConstruct
	public void PostConstruct() {

		try {
			entityManagerFactory = Persistence.createEntityManagerFactory("catchme_model");

		} catch (Exception e) {
			logger.error("Failed to setup persistence unit!", e);
		}

	}

	@PreDestroy
	public void preDestroy() {

		if (entityManagerFactory != null) {
			if (entityManagerFactory.isOpen()) {

				try {
					entityManagerFactory.close();
				} catch (Exception e) {
					logger.error("Failed to close persistence unit!", e);
				}

			}
		}
	}

	@Produces
	@TransactionService
	@RequestScoped
	public EntityManagerService getTransActionManager() {
		if (entityManagerFactory != null) {
			EntityManagerService entityManagerService = new EntityManagerService();
			entityManagerService.setEntityManagerFactory(entityManagerFactory);
			return entityManagerService;
		}
		return null;
	}

}
